//全局数据定义
var newsPicArray=getNewsPicArray(document.getElementsByClassName("first")[0]);
var len=newsPicArray.length;
//console.log(newsPicArray);
//定时器开关标志
var flag;
//图片轮播开始位置
var current=0;

//1显示对应新闻标题、图片、链接
function showPic(whichPic) {
    //显示新闻图片的对象
    var placeholder =document.getElementById("placeholder");
    //显示新闻标题和链接的对象
    var description=document.getElementById("description");
    //显示图片数据
    //图片
    var imgSrc=whichPic.getAttribute("data-image");
    //标题
    var newsTitle=whichPic.getAttribute("title");
    //链接地址
    var url=whichPic.getAttribute("data-url");
    console.log(imgSrc+"|"+newsTitle+"|"+url);
    //设置内容
    placeholder.setAttribute("src",imgSrc);
    description.setAttribute("href",url);
    description.innerText=newsTitle;

    whichPic.parentElement.style.backgroundColor="red"
}

//2默认显示的图片新闻  获得li.first的子标签a
//console.log(document.getElementsByClassName("first")[0].lastElementChild);
//showPic(document.getElementsByClassName("first")[0].firstChild);

//3图片轮播 (定时器) setInterval  setTimeout
//获取图片新闻的相关数据,访问图片新闻(li),相关数据存放到集合中
function getNewsPicArray(cur) {
    var _arr=[];
    while (cur && cur.nodeType === 1){
        _arr.push(cur);
        cur = cur.nextElementSibling;
    }
    return _arr;
}

//图片新闻轮播显示
function circleShowPic() {
    showPic(newsPicArray[current].firstChild);
    flag = setInterval(function () {
        current=++current>len-1?0:current;
        showPic(newsPicArray[current].firstChild);
        newsPicArray[current===0?len-1:current-1].removeAttribute("style");
    },3000);
}

//更改后的a标签点击处理：重新开始图片轮播（重置定时器）
function clickShowPic(whichPic) {
    //停止定时器
    clearInterval(flag);
    //去除图片轮播中当前li标签的背景颜色
    newsPicArray[current].removeAttribute("style");
    //获取点击的索引
    current=parseInt(whichPic.innerText)-1;
    //console.log(current);
    //重新开始定时器
    circleShowPic()
}

circleShowPic();
